import { defineStore } from 'pinia'
import axios, { AxiosError } from 'axios'
import { Config, ConfigCreate, ScanPath, ScanPathCreate } from '../types'

const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || '/api'

// 配置axios默认设置
axios.defaults.timeout = 30000 // 改为30秒超时
axios.defaults.headers.common['Content-Type'] = 'application/json'

// 添加axios拦截器用于调试
axios.interceptors.request.use(
  (config) => {
    console.log('🚀 发送请求:', {
      method: config.method?.toUpperCase(),
      url: config.url,
      baseURL: config.baseURL,
      fullURL: config.baseURL ? config.baseURL + config.url : config.url,
      params: config.params,
      data: config.data,
      headers: config.headers,
      timeout: config.timeout
    })
    return config
  },
  (error) => {
    console.error('❌ 请求拦截器错误:', error)
    return Promise.reject(error)
  }
)

axios.interceptors.response.use(
  (response) => {
    console.log('✅ 收到响应:', {
      status: response.status,
      statusText: response.statusText,
      url: response.config.url,
      data: response.data,
      headers: response.headers
    })
    return response
  },
  (error) => {
    console.error('❌ 响应拦截器错误:', {
      message: error.message,
      code: error.code,
      config: error.config,
      request: error.request,
      response: error.response
    })
    return Promise.reject(error)
  }
)

// 在 useClientStore 中添加新的状态和方法
export const useClientStore = defineStore('client', {
  state: () => ({
    clients: [] as Config[],
    currentScan: null as any,
    scanProgress: {
      taskId: null as string | null,
      status: 'idle' as 'idle' | 'running' | 'completed' | 'failed',
      progress: 0,
      currentStep: '',
      totalSteps: 0,
      completedSteps: 0,
      result: null,
      error: null
    }
  }),

  actions: {
    // 客户端相关操作
    async getClients() {
      try {
        console.log('开始请求配置...')
        const response = await axios.get<Config[]>(`${API_BASE_URL}/config`)
        console.log('配置请求成功:', response.data)
        return response.data
      } catch (error) {
        console.error('配置请求失败:', error)
        if (error instanceof AxiosError && error.response) {
          console.error('错误响应:', error.response.data)
          console.error('状态码:', error.response.status)
        }
        throw error
      }
    },

    async addClient(client: ConfigCreate) {
      const response = await axios.post<Config>(`${API_BASE_URL}/config`, client)
      return response.data
    },

    async updateClient(id: number, client: ConfigCreate) {
      const response = await axios.put<Config>(`${API_BASE_URL}/config/${id}`, client)
      return response.data
    },

    async deleteClient(id: number) {
      await axios.delete(`${API_BASE_URL}/config/${id}`)
    },

    async toggleClient(id: number) {
      const response = await axios.post<Config>(`${API_BASE_URL}/config/${id}/toggle`)
      return response.data
    },

    async testConnection(config: ConfigCreate) {
      const response = await axios.post(`${API_BASE_URL}/config/test`, config)
      return response.data
    },

    // 扫描路径相关操作
    async getScanPaths() {
      try {
        console.log('开始获取扫描路径...')
        const response = await axios.get<ScanPath[]>(`${API_BASE_URL}/scan-paths`)
        console.log('获取扫描路径成功:', response.data)
        return response.data
      } catch (error) {
        console.error('获取扫描路径失败:', error)
        if (error instanceof AxiosError) {
          console.error('错误响应:', error.response?.data)
          console.error('状态码:', error.response?.status)
          console.error('请求URL:', error.config?.url)
        }
        throw error
      }
    },

    async addScanPath(path: ScanPathCreate) {
      try {
        console.log('开始添加扫描路径...', path)
        const response = await axios.post<ScanPath>(`${API_BASE_URL}/scan-paths`, path)
        console.log('添加扫描路径成功:', response.data)
        return response.data
      } catch (error) {
        console.error('添加扫描路径失败:', error)
        if (error instanceof AxiosError) {
          console.error('错误响应:', error.response?.data)
          console.error('状态码:', error.response?.status)
        }
        throw error
      }
    },

    async updateScanPath(path: ScanPath) {
      const response = await axios.put<ScanPath>(`${API_BASE_URL}/scan-paths/${path.id}`, path)
      return response.data
    },

    async deleteScanPath(id: number) {
      await axios.delete(`${API_BASE_URL}/scan-paths/${id}`)
    },

    // 扫描相关操作
    async startGlobalScan() {
      // 不设置超时，因为这只是启动异步任务
      const response = await axios.post(`${API_BASE_URL}/scan/start`)
      return response.data
    },

    async startScan(clientId: number) {
      const response = await axios.post(`${API_BASE_URL}/scan/start/${clientId}`)
      return response.data
    },

    async getScanStatus() {
      const response = await axios.get(`${API_BASE_URL}/scan/status`)
      return response.data
    },

    async getScanResults(status?: string, skip: number = 0, limit: number = 100) {
      const params: any = {}
      if (status) params.status = status
      params.skip = skip
      params.limit = limit
      
      // console.log('getScanResults 发送的请求参数:', params)
      // console.log('getScanResults 发送的完整URL:', `${API_BASE_URL}/scan/results`)
      // console.log('getScanResults 发送的查询字符串:', new URLSearchParams(params).toString())
      
      const response = await axios.get(`${API_BASE_URL}/scan/results`, { 
        params: params,
        paramsSerializer: (params) => {
          const searchParams = new URLSearchParams()
          Object.keys(params).forEach(key => {
            if (params[key] !== undefined && params[key] !== null) {
              searchParams.append(key, String(params[key]))
            }
          })
          return searchParams.toString()
        }
      })
      
      console.log('getScanResults 响应状态:', response.status)
      console.log('getScanResults 响应数据长度:', response.data?.length || 0)
      return response.data
    },

    async getScanResultsCount(status?: string) {
      const params = status ? { status } : {}
      const response = await axios.get(`${API_BASE_URL}/scan/results/count`, { params })
      // 确保返回纯数字，兼容对象和数字格式
      return typeof response.data === 'object' ? response.data.total : response.data
    },

    // 文件操作
    async deleteFiles(fileIds: number[]) {
      try {
        console.log('=== client.ts deleteFiles 开始 ===');
        console.log('deleteFiles 被调用，参数:', fileIds);
        console.log('参数类型:', typeof fileIds, Array.isArray(fileIds));
        console.log('参数长度:', fileIds?.length);
        
        // 确保fileIds是一个有效的数字数组
        if (!Array.isArray(fileIds)) {
          console.error('fileIds不是数组:', fileIds);
          throw new Error('fileIds必须是一个数组');
        }
        
        if (fileIds.length === 0) {
          console.error('fileIds数组为空');
          throw new Error('fileIds数组不能为空');
        }
        
        // 确保所有元素都是数字
        const validFileIds = fileIds.map((id, index) => {
          console.log(`处理第 ${index} 个ID: ${id} (类型: ${typeof id})`);
          const numId = Number(id);
          if (isNaN(numId)) {
            console.error('无效的文件ID:', id);
            throw new Error(`无效的文件ID: ${id}`);
          }
          console.log(`转换结果: ${id} -> ${numId}`);
          return numId;
        });
        
        console.log('验证后的文件ID:', validFileIds);
        
        // 构造正确的请求体格式
        const requestBody = { file_ids: validFileIds };
        console.log('准备发送的请求体:', requestBody);
        console.log('请求体JSON:', JSON.stringify(requestBody));
        console.log('API URL:', `${API_BASE_URL}/files/delete`);
        
        console.log('开始发送删除请求...');
        const response = await axios.post(`${API_BASE_URL}/files/delete`, requestBody);
        
        console.log('删除请求响应状态:', response.status);
        console.log('删除请求响应数据:', response.data);
        console.log('=== client.ts deleteFiles 成功结束 ===');
        
        return response.data;
      } catch (error: any) {
        console.error('=== client.ts deleteFiles 失败 ===');
        console.error('deleteFiles请求失败:', error);
        if (error.response) {
          console.error('错误响应数据:', error.response.data);
          console.error('错误状态码:', error.response.status);
          console.error('错误状态文本:', error.response.statusText);
        }
        if (error.request) {
          console.error('请求配置:', error.config);
          console.error('请求对象:', error.request);
        }
        throw error;
      }
    },

    async getDeleteHistory() {
      const response = await axios.get(`${API_BASE_URL}/files/history`)
      return response.data
    },

    // 轮询扫描进度
    // 轮询扫描进度 - 优化版本
    async pollScanProgress(taskId: string) {
      const maxAttempts = 1200 // 20分钟超时 (1200 * 1秒)
      let attempts = 0
      let consecutiveErrors = 0
      const maxConsecutiveErrors = 5 // 增加容错次数
      
      const poll = async (): Promise<any> => {
        try {
          attempts++
          console.log(`轮询进度，第 ${attempts} 次尝试，任务ID: ${taskId}`)
          
          const response = await axios.get(`${API_BASE_URL}/scan/progress/${taskId}`, {
            timeout: 30000 // 增加到30秒超时
          })
          
          const data = response.data
          console.log('轮询响应数据:', data)
          
          // 重置连续错误计数
          consecutiveErrors = 0
          
          // 更新进度状态
          this.scanProgress = {
            taskId: taskId,
            status: data.status,
            progress: data.progress || 0,
            currentStep: data.current_step || '',
            totalSteps: data.total_steps || 0,
            completedSteps: data.completed_steps || 0,
            error: data.error || null,
            result: data.result || null
          }
          
          if (data.status === 'completed' || data.status === 'failed') {
            console.log('扫描任务完成，状态:', data.status)
            return data
          }
          
          if (attempts >= maxAttempts) {
            throw new Error('扫描超时，请检查后端服务状态')
          }
          
          // 根据任务状态调整轮询间隔
          const pollInterval = data.status === 'running' ? 2000 : 1000 // 运行中2秒，其他1秒
          await new Promise(resolve => setTimeout(resolve, pollInterval))
          return poll()
          
        } catch (error: any) {
          consecutiveErrors++
          console.error(`轮询扫描进度失败 (第${consecutiveErrors}次连续错误):`, error)
          
          // 如果连续错误次数过多，停止轮询
          if (consecutiveErrors >= maxConsecutiveErrors) {
            const errorMessage = error?.response?.data?.detail || error?.message || '网络连接失败'
            console.error('连续错误次数过多，停止轮询')
            this.scanProgress = {
              taskId: taskId,
              status: 'failed',
              progress: 0,
              currentStep: '',
              totalSteps: 0,
              completedSteps: 0,
              error: `连接失败: ${errorMessage}`,
              result: null
            }
            throw new Error(`连接失败: ${errorMessage}`)
          }
          
          // 根据错误类型调整重试策略
          if (error.code === 'ECONNABORTED' || error.message.includes('timeout')) {
            console.log('网络超时，等待10秒后重试...')
            await new Promise(resolve => setTimeout(resolve, 10000))
          } else if (error.response?.status >= 500) {
            console.log('服务器错误，等待5秒后重试...')
            await new Promise(resolve => setTimeout(resolve, 5000))
          } else {
            // 其他错误等待3秒后重试
            await new Promise(resolve => setTimeout(resolve, 3000))
          }
          
          return poll()
        }
      }
      
      return poll()
    },

    // 重置扫描状态
    resetScanProgress() {
      this.scanProgress = {
        taskId: null,
        status: 'idle',
        progress: 0,
        currentStep: '',
        totalSteps: 0,
        completedSteps: 0,
        result: null,
        error: null
      }
    },
    // 在 actions 中添加新方法
    // 设置扫描开始状态
    setScanStarted(taskId?: string) {
      this.scanProgress = {
        taskId: taskId || null,
        status: 'running',
        progress: 0,
        currentStep: '正在启动扫描任务...',
        totalSteps: 0,
        completedSteps: 0,
        result: null,
        error: null
      }
    },
    
    // 更新扫描状态
    updateScanStatus(status: string, progress: number, currentStep: string, error?: string) {
      this.scanProgress.status = status
      this.scanProgress.progress = progress
      this.scanProgress.currentStep = currentStep
      if (error) {
        this.scanProgress.error = error
      }
    }
  }
})
